package com.lqk.nio.groupchat;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;

public class GroupChatClient {
    // 定义相关属性
    private final String HOST="127.0.0.1";  // 服务器IP
    private final int PORT=6667;    // 服务器端口

    private Selector selector;
    private SocketChannel socketChannel;
    private String username;
    // 启动客户端的方法
    public void startClient(String name) throws Exception {
        selector=Selector.open();
        // 连接服务器
        socketChannel=SocketChannel.open(new InetSocketAddress(HOST,PORT));
        // 设置非阻塞模式
        socketChannel.configureBlocking(false);
        // 将socketChannel注册到selector
        socketChannel.register(selector, SelectionKey.OP_READ);
        // 得到username
        username=socketChannel.getLocalAddress().toString().substring(1);
        System.out.println(username+"is ok...");

        // 创建线程
        new Thread(new GroupChatClientThread(selector)).start();

        // 2 向服务端发送消息
        Scanner scanner=new Scanner(System.in);
        while (scanner.hasNext()){
            String msg = scanner.nextLine();
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime time = LocalDateTime.now();
            // LocalDateTime转为String
            String localTime = df.format(time);
            msg=name+"["+username+"-->"+localTime+"]"+" : "+ msg;
            if (msg.length()>0){
                socketChannel.write(Charset.forName("UTF-8").encode(msg));
            }
        }
    }

}
